package com.oig.sys.feign.decode;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.oig.common.exception.BadRequestException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import java.io.IOException;


/**
 * 服务群内的，接口返回400 业务校验逻辑不通过，不熔断
 * 规范校验异常抛出 BadRequestException， 直接向上抛一直到请求Controller，再到统一异常处理器，返回httpStatus=400给前端
 *
 * 而500服务端异常，走fallback处理，调用放根据fallback返回值判断
 *
 * 用sentinel 需要重写sentinelHandler才行， 先不开启服务降级
 */
@Slf4j
public class BadRequestDecoder extends ErrorDecoder.Default {

    @Override
    public Exception decode(String methodKey, Response response) {
        /*
         * 400异常不走fallback,不熔断
         */
        if (response.status() == HttpStatus.BAD_REQUEST.value() || response.status() == HttpStatus.UNAUTHORIZED.value()){
            String body = null;
            try{
                if (response.body()==null){
                    String url = null;
                    try {
                        //异常提示 方便查询日志
                        url = response.request().url();
                    }catch (Exception ignore){
                        throw new BadRequestException("feign error");
                    }
                    throw new BadRequestException("feign error" + url) ;
                }
                body = Util.toString(response.body().asReader(Util.UTF_8)) ;
                log.info("feign error msg:{}", body);
                if (body!=null && body.contains("msg") && body.contains("code")){
                    JSONObject jsonObject = JSON.parseObject(body);
                    body = jsonObject.getString("msg");
                }
            } catch (IOException ex){
                log.error("feign decoder error",ex);
            }
            return new BadRequestException(body);
        }

        // 如果不是400，还是交给Default去解码处理
        return super.decode(methodKey, response);
    }
}
